package balmysundaycandy.extention.datastore;

import balmysundaycandy.more.low.level.NotWorkOnAppengineEnvironment;
import balmysundaycandy.more.low.level.WorkOnAppengineEnvironment;
import balmysundaycandy.more.low.level.WorkOnLocalEnvironment;
import balmysundaycandy.more.low.level.datastore.DatastoreOperations;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityTranslator;
import com.google.apphosting.api.ApiProxy;
import com.google.apphosting.api.DatastorePb.GetRequest;
import com.google.apphosting.api.DatastorePb.GetResponse;
import com.google.apphosting.api.DatastorePb.GetSchemaRequest;
import com.google.apphosting.api.DatastorePb.Schema;
import com.google.storage.onestore.v3.OnestoreEntity.Path;
import com.google.storage.onestore.v3.OnestoreEntity.Reference;
import com.google.storage.onestore.v3.OnestoreEntity.Path.Element;

/**
 * provide a datasrore utils.
 * 
 * @author marblejenka
 */
public class Datastore {
	private String appid;

	public Datastore() {
		this.appid = ApiProxy.getCurrentEnvironment().getAppId();
	}

	/**
	 * get entity from datastore identified kind and id.
	 * 
	 * @param kind
	 *            kind name
	 * @param id
	 * @return Enity Object
	 */
	@WorkOnAppengineEnvironment
	@WorkOnLocalEnvironment
	public Entity get(String kind, Long id) {
		return EntityTranslator.createFromPb(getByProtocolBuffer(kind, id).entitys().get(0).getEntity());
	}

	/**
	 * get "get response" as protocol buffer expression from datastore.
	 * 
	 * @param kind
	 *            kind name
	 * @param id
	 *            id
	 * @return GetResponse object
	 */
	@WorkOnAppengineEnvironment
	@WorkOnLocalEnvironment
	public GetResponse getByProtocolBuffer(String kind, Long id) {
		Element element = new Element();
		element.setId(id);
		element.setType(kind);

		Path path = new Path();
		path.addElement(element);

		Reference reference = new Reference();
		reference.setApp(appid);
		reference.setPath(path);

		GetRequest getRequest = new GetRequest();
		getRequest.addKey(reference);

		GetResponse getResponse = DatastoreOperations.GET.call(getRequest);

		return getResponse;
	}

	/**
	 * get soft scheme information from datastore.
	 */
	@NotWorkOnAppengineEnvironment
	@WorkOnLocalEnvironment
	public Schema getScheme() {
		GetSchemaRequest getSchemaRequest = new GetSchemaRequest();
		getSchemaRequest.setApp(appid);

		Schema schema = DatastoreOperations.GET_SCHEMA.call(getSchemaRequest);

		return schema;
	}
}
